package com.sharedlease.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sharedlease.check.ReviewUtil;
import com.sharedlease.dto.IndentDTO;
import com.sharedlease.entity.*;
import com.sharedlease.service.ChatService;
import com.sharedlease.service.ProductService;
import com.sharedlease.service.impl.ProductServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 吴钟富
 * @since 2021-03-02
 */
@RestController
@Api(tags = "产品相关接口")
@RequestMapping("/product")
public class ProductController {
    @Autowired
    public ProductService productService;

    @Autowired
    public ChatService chatService;

    @Autowired
    public JdbcTemplate jdbcTemplate;

    @GetMapping("/getById/{id}")
    @ApiOperation("根据一个id查询合法产品")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "要查询的产品id", defaultValue = "1"),

    }
    )
    public Product getById(@PathVariable Long id) {
        System.out.println("id:" + id);
        Product product = productService.getById(id);
        return product;
    }


    @GetMapping("/list")
    @ApiOperation("查询全部审核通过的产品")
    public List<Product> list() {
        QueryWrapper<Product> wrapper = new QueryWrapper<>();
        wrapper.eq("legal", "1");
        List<Product> list = productService.list(wrapper);
        return list;
    }

    @GetMapping("/listAll")
    @ApiOperation("查询全部产品(任何审核状态都查询)")
    public List<Product> listAll() {
        List<Product> list=null;
        ProductServiceImpl service = new ProductServiceImpl();
        List<Product> allProductsFromRedis = service.getAllProductsFromRedis();
        if (allProductsFromRedis==null){
            list = this.productService.list(null);
            service.saveAllProductsToRedis(list);
            System.out.println("redis中没有，从mysql中拿并且存到redis中了");
            return list;
        }
        System.out.println("redis中有，直接返回了");
        return allProductsFromRedis;

    }

    @GetMapping("/listAll/{legal}")
    @ApiOperation("查询合法性为x的产品")
    public List<Product> listByLegal(@PathVariable String legal) {
        QueryWrapper<Product> wrapper = new QueryWrapper<>();
        wrapper.eq("legal", legal);
        List<Product> list = productService.list(wrapper);
        return list;
    }


    @PostMapping("/save")
    @ApiOperation("上传产品")
    public R save(@RequestBody Product product) {
        syncLegal(product, false);
        return R.ok();
    }

    private void syncLegal(Product product, boolean flag) {
        String s = product.get_title_desc_rule();
        new Thread(() -> {
            try {
                ReviewUtil.review(s, productService, chatService, product, flag);
            } catch (Exception e) {
                System.out.println("syncLegal error" + e.getMessage());
            }
        }).start();
    }

    @PostMapping("/isProductLegal")
    @ApiOperation("判断产品是否合法")
    public boolean isProductLegal(@RequestBody Product product) {
        String s = product.get_title_desc_rule();
        return true;
    }

    @PutMapping("/update")
    @ApiOperation("根据id更改一个产品")
    R update(@RequestBody Product product) {
        syncLegal(product, true);
        return R.ok();
    }

    @DeleteMapping("/removeById/{id}")
    @ApiOperation("根据id删除一个产品")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "要删除的产品id", defaultValue = "-1"),

    }
    )
    R removeById(@PathVariable Long id) {

        return R.operate(productService.removeById(id));
    }

    @GetMapping("/search")
    @ApiOperation("搜索合法产品,content的值可以为空格，但是不能什么都没有")
    public List<Product> search(@RequestParam String content) {
        List<Product> list;
        final String content1 = content.trim();
        if (!content.equals("")) {
            QueryWrapper<Product> wrapper = new QueryWrapper<>();
            wrapper.eq("legal", "1");
            wrapper.and(x ->
                    x.like("title", content1)
                            .or()
                            .like("description", content1)
                            .or()
                            .like("rent_rule", content1)
                            .or()
                            .like("tag", content1)
            );

            list = productService.list(wrapper);
        } else {
            QueryWrapper<Product> wrapper = new QueryWrapper<>();
            wrapper.eq("legal", "1");
            list = productService.list(wrapper);
        }
        System.out.println(list);
        return list;
    }

    @PostMapping("/getRecommendProducts")
    @ApiOperation("根据用户浏览记录得到合法推荐产品")
    public List<Product> list(@RequestBody List<Record> list) {
        List<Product> all;
        HashSet<String> set = new HashSet<>();
        for (int i = 0; i < list.size(); i++) {
            String tag = list.get(i).getTag();
            set.add(tag);
        }

        String sql = "select * from product where (id=-9527";

        for (String s : set) {
            sql += (" or tag='" + s + "'");
        }
        sql += ") and legal=1";
        System.out.println(sql);
        RowMapper<Product> rowMapper = new BeanPropertyRowMapper<Product>(Product.class);
        List<Product> productList = jdbcTemplate.query(sql, rowMapper);
        return productList;
    }

    @PostMapping("/getProductsByIndentList")
    @ApiOperation("根据订单列表查询合法产品列表")
    public List<Product> getProductsByIndentList(@RequestBody List<Indent> list) {
        List<Product> all;
        HashSet<Long> set = new HashSet<>();
        for (int i = 0; i < list.size(); i++) {
            Long pid = list.get(i).getPid();
            set.add(pid);

        }
        String sql = "select * from product where (id=-9527";

        for (Long tem : set) {
            sql += (" or id=" + tem);
        }
        sql += ") and legal=1";
        System.out.println(sql);
        RowMapper<Product> rowMapper = new BeanPropertyRowMapper<Product>(Product.class);
        List<Product> productList = jdbcTemplate.query(sql, rowMapper);
        return productList;
    }

    @PostMapping("/getProductsByCollectProductList")
    @ApiOperation("根据收藏产品记录查询合法产品列表")
    public List<Product> getProductsByCollectProductList(@RequestBody List<Collect_product> list) {
        List<Product> all;
        HashSet<Long> set = new HashSet<>();
        for (int i = 0; i < list.size(); i++) {
            Long pid = list.get(i).getPid();
            set.add(pid);

        }
        String sql = "select * from product where (id=-9527";
        for (Long tem : set) {
            sql += (" or id=" + tem);
        }
        sql += ") and legal=1";
        System.out.println(sql);
        RowMapper<Product> rowMapper = new BeanPropertyRowMapper<Product>(Product.class);
        List<Product> productList = jdbcTemplate.query(sql, rowMapper);
        return productList;
    }

    @GetMapping("/recommandBaseUserCF/{uid}")
    @ApiOperation("基于用户的协同过滤推荐,如果用户没有租或买过东西，推荐订单表里的所有产品")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uid", value = "推荐产品的目标用户id，即给uid推荐产品", defaultValue = "1"),

    }
    )
    public List<Product> recommandBaseUserCF(@PathVariable Long uid) {
        String sql="select uid,pid from indent";
        RowMapper<IndentDTO> rowMapper=new BeanPropertyRowMapper<>(IndentDTO.class);
        List<IndentDTO> indentDTOS = jdbcTemplate.query(sql, rowMapper);
        ProductServiceImpl proService = new ProductServiceImpl();
        Set<Long> recmmandPros = proService.recommandBaseUserCF(uid,indentDTOS);
        QueryWrapper<Product> wrapper = new QueryWrapper<>();
        wrapper.eq("id","-1");
        for(Long pid:recmmandPros){
            wrapper.or();
            wrapper.eq("id",pid);
        }
        List<Product> list = productService.list(wrapper);
        return list;

    }

    @GetMapping("/recommandBaseItemCF/{uid}")
    @ApiOperation("基于物品的协同过滤推荐,如果用户没有租或买过东西，推荐订单表里的所有产品")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uid", value = "推荐产品的目标用户id，即给uid推荐产品", defaultValue = "1"),

    }
    )
    public List<Product> recommandBaseItemCF(@PathVariable Long uid) {
        String sql="select uid,pid from indent";
        RowMapper<IndentDTO> rowMapper=new BeanPropertyRowMapper<>(IndentDTO.class);
        List<IndentDTO> indentDTOS = jdbcTemplate.query(sql, rowMapper);
        ProductServiceImpl proService = new ProductServiceImpl();
        Set<Long> recmmandPros = proService.recommandBaseItemCF(uid,indentDTOS);
        QueryWrapper<Product> wrapper = new QueryWrapper<>();
        wrapper.eq("id","-1");
        for(Long pid:recmmandPros){
            wrapper.or();
            wrapper.eq("id",pid);
        }
        List<Product> list = productService.list(wrapper);
        return list;

    }


}

